<template>
  <div class="com-container">
    <div class="com-chart" ref="stock_ref"></div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import《组件名称》from'《组件路径》';
import { mapState } from "vuex";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
      chartEntity: null,
      allData: null,
      currIndex: 0,
      timer: null,
    };
  },
  //计算属性:类似于data概念,有缓存效果,用于不经常修改的数据
  computed: {
    ...mapState(["theme"]),
  },
  // 监控data中的数据变化
  watch: {
    theme() {
      // 销毁当前图表
      this.chartEntity.dispose();
      this.initChart();
      this.screenAdapter();
      this.updateChart();
    },
  },
  //方法集合
  methods: {
    initChart() {
      this.chartEntity = this.$echarts.init(this.$refs.stock_ref, this.theme);
      let option = {
        title: {
          text: "库存和销量分析",
          left: 20,
          top: 20,
        },
      };
      this.chartEntity.setOption(option);
      this.chartEntity.on("mouseover", () => clearInterval(this.timer));
      this.chartEntity.on("mouseout", () => this.startInterval());
    },
    getData(ret) {
      // let { data: ret } = await this.$http.get("stock");
      this.allData = ret;
      // 刷新图表
      this.updateChart();
      this.startInterval();
    },
    updateChart() {
      let centerArr = [
        ["18%", "40%"],
        ["50%", "40%"],
        ["82%", "40%"],
        ["34%", "75%"],
        ["66%", "75%"],
      ];

      let colorArr = [
        ["#4FF778", "#0BA82C"],
        ["#E5DD45", "#E8B11C"],
        ["#E8821C", "#E55445"],
        ["#5052EE", "#AB6EE5"],
        ["#23E5E5", "#2E72BF"],
      ];

      let start = this.currIndex * 5;
      let end = (this.currIndex + 1) * 5;

      let showData = this.allData.slice(start, end);
      let seriesArr = showData.map((item, index) => {
        return {
          type: "pie",
          center: centerArr[index],
          emphasis: {
            scale: false, //移入时环不缩小
          },
          labelLine: {
            show: true,
          },
          label: {
            // position: "outside", //center会莫名其妙的导致字会消失
            show: true,
            color: colorArr[index][0],
          },
          data: [
            {
              name: item.name + "\n" + item.sales,
              value: item.sales,
              itemStyle: {
                color: new this.$echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  {
                    offset: 0,
                    color: colorArr[index][0],
                  },
                  {
                    offset: 1,
                    color: colorArr[index][1],
                  },
                ]),
              },
            },
            {
              value: item.stock,
              itemStyle: {
                color: "#333843",
              },
            },
          ],
        };
      });
      let dataOption = {
        series: seriesArr,
      };
      this.chartEntity.setOption(dataOption);
    },
    // 根据屏幕大小调整分辨率
    screenAdapter() {
      let title_font_size = (this.$refs.stock_ref.offsetWidth / 100) * 3.6;
      let innerRadius = title_font_size * 2.5;
      let outRadius = innerRadius * 1.125;

      let seriesArr = [];
      for (let i = 0; i < 5; i++) {
        let s = {
          type: "pie",
          radius: [outRadius, innerRadius],
          label: {
            fontSize: title_font_size / 2.5,
          },
        };
        seriesArr.push(s);
      }
      let adapterOption = {
        title: {
          textStyle: {
            fontSize: title_font_size,
          },
        },
        series: seriesArr,
      };
      this.chartEntity.setOption(adapterOption);
      this.chartEntity.resize();
    },
    startInterval() {
      if (this.timer) {
        clearInterval(this.timer);
      }
      this.timer = setInterval(() => {
        this.currIndex++;
        if (this.currIndex > 1) {
          this.currIndex = 0;
        }
        this.updateChart();
      }, 5000);
    },
  },
  beforeCreate() {}, //生命周期-创建之前
  created() {
    this.$socket.registerCallBack("stock", this.getData);
  }, //生命周期-创建完成（可以访问当前this实例）
  beforeMount() {}, //生命周期-挂载之前
  mounted() {
    this.initChart();
    // this.getData();
    this.$socket.send({
      action: "getData",
      socketType: "stock",
      chartName: "stock",
      value: "",
    });

    // 不要在函数中加(), 否则只会调用一次
    window.addEventListener("resize", this.screenAdapter);
    // 加载完成后自动适配分辨率
    this.screenAdapter();
  }, //生命周期-挂载完成（可以访问DOM元素）
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  beforeUpdate() {}, //生命周期-更新之前
  updated() {}, //生命周期-更新之后
  beforeDestroy() {}, //生命周期-销毁之前
  destroyed() {
    window.removeEventListener("resize", this.screenAdapter);
    clearInterval(this.timer);
    this.$socket.unRegisterCallBack("stock");
  }, //生命周期-销毁完成
};
</script>

<style lang="less" scoped>
.arr-l,
.arr-r {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  color: #fff;
  cursor: pointer;
}
.arr-l {
  left: 10%;
}
.arr-r {
  right: 10%;
}
.cat-name {
  position: absolute;
  right: 15%;
  bottom: 15%;
  color: #fff;
}
</style>